package login.servlet;

import login.dao.UserDao;
import login.dao.UserDaoImpl;
import login.daomain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/29 8:46
 **/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    /**1.设置post请求编码，解决中文乱码问题
    * 2.获取请求参数（用户输入的内容）
    * 3.若需要，将参数封装成对象
    * 4.调用dao层的方法完成登陆功能（查询操作）
    * 5.根据dao层方法的返回值
    *   若不为空，表示用户名密码正确，将用户名保存在域对象，转发到succServlet（登录成功界面）
    *   若为空，表示用户名或密码错误，转发到failServlet
    * */
    private static UserDaoImpl dao;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name =req.getParameter("name");
        String password =req.getParameter("password");
        User user= dao.login(name,password);
        if (user!=null){
            //成功
            req.setAttribute("user",user.getName());
            req.getRequestDispatcher("/successServlet").forward(req,resp);
        }else {
            req.setAttribute("login_error","用户名或密码错误");
            req.getRequestDispatcher("/failServlet");
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
